package core;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import model.Authentication;
import model.FacebookEvent;
import model.UserInfo;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class GCalUpdate {

	private UserInfo userInfo;

	public GCalUpdate(UserInfo userInfo) {
		this.userInfo = userInfo;
	}

	public void doUpdate() {

		List<FacebookEvent> fbEvents = null;

		try {
			fbEvents = getFbEvents(userInfo);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (java.text.ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		exportToGCal(fbEvents);

	}

	private void exportToGCal(List<FacebookEvent> fbEvents) {

		GCal gcal = new GCal(new Authentication(userInfo.getGoogleUsername(), userInfo.getGooglePassword()));
		boolean alreadyHaveCalendar = gcal.getCalendar();
		
		if( !alreadyHaveCalendar )
			gcal.createCalendar();
		gcal.addEvents(fbEvents);
	}

	private List<FacebookEvent> getFbEvents(UserInfo userInfo)
			throws IOException, ParseException, java.text.ParseException {
		URL fbSite = new URL("https://graph.facebook.com/"
				+ userInfo.getFbUserId() + "/events?access_token="
				+ userInfo.getFbAccessToken());
		System.out.println("Trying to get events from URL " + fbSite.toString());
		URLConnection conn = fbSite.openConnection();
		BufferedReader in = new BufferedReader(new InputStreamReader(
				conn.getInputStream()));
		String contents = "";
		String inputLine;

		while ((inputLine = in.readLine()) != null)
			contents += inputLine;

		in.close();

		JSONParser parser = new JSONParser();
		JSONObject obj = (JSONObject) parser.parse(contents);
		JSONArray eventArr = (JSONArray) obj.get("data");
		
		List<FacebookEvent> events = new LinkedList<FacebookEvent>();

		for (int i = 0; i < eventArr.size(); i++) {
			JSONObject eventObj = (JSONObject) eventArr.get(i);
			
			String name = (String) eventObj.get("name");
			String location = (String) eventObj.get("location");
			
			String start = (String) eventObj.get("start_time");
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
			Date startDate = format.parse(start);
			
			String end = (String) eventObj.get("end_time");
			Date endDate = format.parse(end);
			
			FacebookEvent event = new FacebookEvent(name, location, startDate, endDate);
			events.add(event);
		}
		System.out.println(events.toString());
		return events;
	}
}
